﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace 采集网页邮箱电话
{
    public partial class Form1 : Form
    {
        //CancellationTokenSource tokenSource;
        //ManualResetEvent resetEvent;
        //bool a = false;
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;//duo xian cheng
            //button3.Enabled= false;
            richTextBox1.ReadOnly= true;
            richTextBox1.BackColor = Color.White;
            richTextBox1.ForeColor = Color.DodgerBlue;
            richTextBox1.Focus();
            richTextBox2.ReadOnly = true;
            richTextBox2.BackColor = Color.White;
            richTextBox2.ForeColor = Color.DodgerBlue;
            richTextBox2.Focus();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //if (tokenSource != null)
            //{
            //    tokenSource.Cancel();
            //}
//
            //tokenSource = new CancellationTokenSource();
            //resetEvent = new ManualResetEvent(true);
            //CancellationToken token = tokenSource.Token;

            Task task = new Task(() =>
            {
                try
                {
                
                string file_name = "ID.xlsx";//文件路径，此处为了省事，直接把文件放到了bin->Debug-文件夹下

                
                string conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file_name + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";//连接数据源所用的字符串
                
                OleDbConnection con = new OleDbConnection(conString);//创建连接
                con.Open();//打开连接
                string sql = "select * from [Sheet1$]";//查询语句

                OleDbDataAdapter adp = new OleDbDataAdapter(sql, con);//执行查询语句
                DataSet ds = new DataSet();//可以理解未内存中的一个数据库，里边会有多张表
                adp.Fill(ds);//将查询结果填充到DataSet中
                con.Close();//关闭连接
                con.Dispose();//释放资源
                DataTableCollection datatable_collection = ds.Tables;//得到一个数据表的集合
                DataTable dt = datatable_collection[0];//第一张表就是我们的数据

                    richTextBox1.Focus();
                    richTextBox1.Clear();
                    richTextBox1.AppendText("所属省份,所属城市,所属区县,网址,邮箱" + System.Environment.NewLine);
                    richTextBox2.Focus();
                    richTextBox2.Clear();
                    richTextBox2.AppendText("所属省份,所属城市,所属区县,网址,电话" + System.Environment.NewLine);
                    File.AppendAllText("邮箱res.txt", "所属省份,所属城市,所属区县,网址,邮箱" + System.Environment.NewLine);
                    File.AppendAllText("电话res.txt", "所属省份,所属城市,所属区县,网址,电话" + System.Environment.NewLine);
                    label2.Text = "正在采集中...";

                    button1.Enabled = false;
                    button2.Enabled = false;
                    button4.Enabled = false;
                    button5.Enabled = false;
                    button6.Enabled = false;
                    button7.Enabled = false;

                    foreach (DataRow dr in dt.Rows)
                {
                    string shengfen = dr[0].ToString();
                    string chengshi = dr[1].ToString();
                    string quxian = dr[2].ToString();
                    string wangzhi = dr[3].ToString();
                    //richTextBox1.AppendText(t1 + ",");
                    string url = "http://" + wangzhi;
                    WebClient client = new WebClient();
                    client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41");
                    try
                    {
                        string html = client.DownloadString(url);

                        Regex regex = new Regex(@"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b");
                        //Regex regph = new Regex(@"\b/1[3456789]\d{9}/\b");
                        MatchCollection matches = regex.Matches(html);

                        Regex regex2 = new Regex(@"(1[3|4|5|6|7|8|9]\d{9})");
                        //Regex regph = new Regex(@"\b/1[3456789]\d{9}/\b");
                        MatchCollection matches2 = regex2.Matches(html);
                        // 输出提取到的邮箱地址
                        foreach (Match match in matches)
                        {
                            string youxiang = match.Value;

                            richTextBox1.AppendText(shengfen + "," + chengshi + "," + quxian + "," + wangzhi + "," + youxiang + System.Environment.NewLine);
                            File.AppendAllText("邮箱res.txt", shengfen + "," + chengshi + "," + quxian + "," + wangzhi + "," + youxiang + System.Environment.NewLine);
                        }

                        foreach (Match match2 in matches2)
                        {
                            string dianhua = match2.Value;

                            richTextBox2.AppendText(shengfen + "," + chengshi + "," + quxian + "," + wangzhi + "," + dianhua + System.Environment.NewLine);
                            File.AppendAllText("电话res.txt", shengfen + "," + chengshi + "," + quxian + "," + wangzhi + "," + dianhua + System.Environment.NewLine);
                        }

                    }
                    catch (Exception )
                    {
                        //MessageBox.Show(ex.Message);
                    }
                }
                label2.Text = "采集结束！";
                button1.Enabled = true;
                button2.Enabled = true;
                button4.Enabled = true;
                button5.Enabled = true;
                button6.Enabled = true;
                button7.Enabled = true;
                MessageBox.Show("采集完成！");
                    //Form okk = new ok();
                    //okk.Show();
                }
                catch
                {
                    Form err = new err();
                    err.ShowDialog();

                }

            }//token
            );
            task.Start();
            
            

        }


        private void button2_Click_1(object sender, EventArgs e)
        {
            try 
            {
                System.Diagnostics.Process.Start("ID.xlsx");

            }
            catch 
            {
                MessageBox.Show("模板文件不存在！");
                try {
                WebRequest request = WebRequest.Create("https://dogecloud.suluo.online/soft/%E9%87%87%E9%9B%86%E5%8A%A9%E6%89%8B/ID.xlsx");
                WebResponse response = request.GetResponse();
                if (response.ContentType.ToLower().Length > 0)
                {
                    using (Stream reader = response.GetResponseStream())
                    {
                        using (FileStream writer = new FileStream(@".\ID.xlsx", FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            byte[] buffer = new byte[1024];
                            int c = 0;
                            while ((c = reader.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                writer.Write(buffer, 0, c);
                                   // string path = ".\\ID.xlsx";
                                   // bool result = File.Exists(path);
                                   // if (result == true)
                                   // {
                                  //      richTextBox2.AppendText("下载完成" + System.Environment.NewLine + System.Environment.NewLine);
                                  //  }
                                }
                        }
                    }

                    //richTextBox2.AppendText("ok");
                }
                    richTextBox2.AppendText("正在下载模板文件，请稍后..." + System.Environment.NewLine + System.Environment.NewLine);
                    richTextBox2.AppendText("下载完成" + System.Environment.NewLine + System.Environment.NewLine);
                }
                catch 
                {
                    MessageBox.Show("出现致命错误，请检测网络连接！");

                }
                
            }
        }

        
        private void button3_Click(object sender, EventArgs e)
        {/*
            Task taskdh = new Task(() =>
            {
            richTextBox1.Focus();
            richTextBox1.Clear();
            richTextBox1.AppendText("所属省份,所属城市,所属区县,网址,邮箱" + System.Environment.NewLine);
            File.AppendAllText("res.txt", "所属省份,所属城市,所属区县,网址,邮箱" + System.Environment.NewLine);
            label2.Text = "正在采集中...";

            button1.Enabled = false;
            button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
            button5.Enabled = false;
            button6.Enabled = false;
            button7.Enabled = false;
            string file_name = "ID.xlsx";//文件路径，此处为了省事，直接把文件放到了bin->Debug-文件夹下
            string conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file_name + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";//连接数据源所用的字符串
            OleDbConnection con = new OleDbConnection(conString);//创建连接
            con.Open();//打开连接
            string sql = "select * from [Sheet1$]";//查询语句

            OleDbDataAdapter adp = new OleDbDataAdapter(sql, con);//执行查询语句
            DataSet ds = new DataSet();//可以理解未内存中的一个数据库，里边会有多张表
            adp.Fill(ds);//将查询结果填充到DataSet中
            con.Close();//关闭连接
            con.Dispose();//释放资源
            DataTableCollection datatable_collection = ds.Tables;//得到一个数据表的集合
            DataTable dt = datatable_collection[0];//第一张表就是我们的数据
            foreach (DataRow dr in dt.Rows)
            {
                string shengfen = dr[0].ToString();
                string chengshi = dr[1].ToString();
                string quxian = dr[2].ToString();
                string wangzhi = dr[3].ToString();
                //richTextBox1.AppendText(t1 + ",");
                string url = "http://" + wangzhi;
                WebClient client = new WebClient();
                client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41");
                try
                {
                    string html = client.DownloadString(url);

                        Regex regex = new Regex(@"(1[3|4|5|6|7|8|9]\d{9})");
                        //Regex regph = new Regex(@"\b/1[3456789]\d{9}/\b");
                        MatchCollection matches = regex.Matches(html);

                    // 输出提取到的邮箱地址
                    foreach (Match match in matches)
                    {
                        string dianhua = match.Value;

                        richTextBox1.AppendText(shengfen + "," + chengshi + "," + quxian + "," + wangzhi + "," + dianhua + System.Environment.NewLine);
                        File.AppendAllText("电话res.txt", shengfen + "," + chengshi + "," + quxian + "," + wangzhi + "," + dianhua + System.Environment.NewLine);
                    }

                }
                catch (Exception)
                {
                    //MessageBox.Show(ex.Message);
                }
            }
            label2.Text = "采集结束！";
            button1.Enabled = true;
            button2.Enabled = true;
                button3.Enabled = true;
                button4.Enabled = true;
            button5.Enabled = true;
            button6.Enabled = true;
            button7.Enabled = true;
            //MessageBox.Show("邮件采集完成！");
            Form okk = new ok();
            okk.Show();


        }//token
            );
            taskdh.Start();*/

        }

        private void button4_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            richTextBox2.Clear();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Form ab = new about();
            ab.ShowDialog();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            File.WriteAllText("邮箱res.txt", "");
            File.WriteAllText("电话res.txt", "");
            MessageBox.Show("清空完成！");
        }

        private void button7_Click(object sender, EventArgs e)
        {
            try { 
            System.Diagnostics.Process.Start("邮箱res.txt");
            System.Diagnostics.Process.Start("电话res.txt");
            }
            catch 
            {
                MessageBox.Show("文件不存在！");
            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.SelectionLength = 0;
            richTextBox1.Focus();
            richTextBox2.SelectionStart = richTextBox2.Text.Length;
            richTextBox2.SelectionLength = 0;
            richTextBox2.Focus();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //新版本检测
            try { 
            string url = "http://suluo.online/csharp/tools/htmlcaijiver.txt";
                string sq = "http://suluo.online/csharp/tools/htmlcaijishouquan.txt";
                WebClient client = new WebClient();
            client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41");
            string html = client.DownloadString(url);
                string sqres = client.DownloadString(sq);
                if (sqres != "qhpublic")
                {
                    MessageBox.Show("未授权");
                    System.Environment.Exit(0);
                }

                //label2.Text = "最新版本：" + html;
                string str = string.Join("", html.Split('.'));
            long res = long.Parse(str);
            if (res - 1000 > 0)
            {
                richTextBox1.AppendText("当前版本：1.0.0.0" + System.Environment.NewLine + System.Environment.NewLine);
                richTextBox1.AppendText("正在检查新版本..." + System.Environment.NewLine + System.Environment.NewLine);
                richTextBox1.AppendText("最新版本："+html + System.Environment.NewLine + System.Environment.NewLine);
                richTextBox1.AppendText("请更新到最新版本。" + System.Environment.NewLine + System.Environment.NewLine);
                richTextBox1.AppendText("https://suluo.online/csharp/tools/采集助手.html" + System.Environment.NewLine + System.Environment.NewLine);
            }
            else
            {
                richTextBox1.AppendText("当前版本：1.0.0.0" + System.Environment.NewLine + System.Environment.NewLine);
                richTextBox1.AppendText("正在检查新版本..." + System.Environment.NewLine + System.Environment.NewLine);
                richTextBox1.AppendText("当前版本为最新版本。" + System.Environment.NewLine);
            }
            }
            catch 
            {
                MessageBox.Show("出现致命错误，请检测网络连接！");
            }

        }
    }
}
